package blockChain;

import com.google.gson.GsonBuilder;

import java.security.MessageDigest;

/**
 * @author WuYongheng
 * @date 2022/10/22
 * @description 工具类，负责加密，返回‘困难度’个零，解析json数据
 */
public class StringUtil {
    /**
     * for循环的解释：0xff & hash[i]
     *
     * @param input 未加密的字符串
     * @return 加密之后的字符串
     */
    public static String applySha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
//            传入需要计算的字符串，把输入变成ascii值
            byte[] hash = digest.digest(input.getBytes("UTF-8"));
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 困难度是多少，就返回多少个零
     * 比如 difficulty=6 返回 000000
     *
     * @param difficulty 困难度
     * @return 一个字符串
     */
    public static String getDifficultyString(int difficulty) {
        return new String(new char[difficulty]).replace('\0', '0');
    }

    /**
     * 将数据以json的格式显示
     *
     * @param o
     * @return
     */
    public static String getJson(Object o) {
        return new GsonBuilder().setPrettyPrinting().create().toJson(o);
    }

}
